package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.OrderModel;
import models.OrderProductModel;
import models.StaffModel;
import models.StoreItemModel;
import models.TransactionModel;
import search.OrderSearchData;
import admin.data.OrderData;
import admin.data.StoreItemData;
import admin.data.TransactionData;

@SuppressWarnings("serial")
public class DirectSellServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(DirectSellServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		process(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String action = request.getParameter("action");

			if (action != null && action.equals("view")) {
				String id = request.getParameter("id");
				OrderModel order = OrderData.getById(id);
				request.setAttribute("order", order);
				request.setAttribute("url", request.getRequestURL().toString());
				request.getRequestDispatcher(
						"/admin/pages/order_sell_direct.jsp").forward(request,
						response);
			} else if (action != null && action.equals("finish")) {
				boolean check = true;
				TimeZone localTimeZone = TimeZone.getTimeZone("GMT+07:00");
				TimeZone.setDefault(localTimeZone);
				Calendar.getInstance().setTimeZone(localTimeZone);
				HttpSession session = request.getSession();
				StaffModel staff = (StaffModel) session
						.getAttribute("staff_logged_in");
				String id = request.getParameter("id");
				OrderModel order = OrderData.getById(id);
				List<String> listStringProduct = order.getListOrderProduct();
				List<StoreItemModel> listStoreItem = new ArrayList<StoreItemModel>();
				List<TransactionModel> listTransaction = new ArrayList<TransactionModel>();
				StoreItemData storeItemData = new StoreItemData();
				TransactionData transactionData = new TransactionData();
				StoreItemModel storeItemModel;
				for (String string : listStringProduct) {
					OrderProductModel orderPr = new OrderProductModel();
					orderPr.getValueFromString(string);
					storeItemModel = new StoreItemModel();
					storeItemModel = storeItemData.getItem(orderPr
							.getProductId());
					if (storeItemModel != null
							&& (storeItemModel.getInventory() >= orderPr
									.getQuantity())) {
						// nếu đơn hàng chưa xử lý
						if (order.getStatus() == 1) {
							storeItemModel.setInventory(storeItemModel
									.getInventory() - orderPr.getQuantity());
							listStoreItem.add(storeItemModel);
							// thực hiện lưu transaction.
							TransactionModel transaction = new TransactionModel();
							transaction
									.setTransactionId(IdUniqueHelper.getId());
							transaction.setDealId(storeItemModel.getDealId());
							transaction.setStoreItemId(storeItemModel.getId());
							transaction.setInventory(storeItemModel
									.getInventory());
							transaction.setDelivered(storeItemModel
									.getDelivered());
							transaction.setDelivery(storeItemModel
									.getDelivery());
							transaction.setLoc(storeItemModel.getLoc());
							transaction.setType(0);
							transaction.setDate(Calendar.getInstance()
									.getTime());
							transaction.setAmount(orderPr.getQuantity());
							listTransaction.add(transaction);
						}

					} else {
						check = false;
					}
				}
				if (check) {
					for (int i = 0; i < listStoreItem.size(); i++) {
						storeItemData.insert(listStoreItem.get(i));
						transactionData.insert(listTransaction.get(i));
					}
					order.setSalername(staff.getUsername());
					order.setStatus(4);
					order.setCheckOut(true);
					order.setCheckOutTime(Calendar.getInstance().getTime());
					OrderData.insert(order);

					request.setAttribute("order", order);
					request.setAttribute("url", request.getRequestURL()
							.toString());
					request.getRequestDispatcher(
							"/admin/pages/order_sell_direct.jsp").forward(
							request, response);
				} else {
					session.setAttribute("",
							"Số lượng sản phẩm trong kho không đủ hoàn thành đơn hàng !");
					response.sendRedirect("/admin/sell/direct");
				}

			} else {
				int page = 1;
				try {
					page = Integer.parseInt((String) request
							.getParameter("page"));
				} catch (Exception e) {
					page = 1;
				}
				OrderSearchData orderSearch = new OrderSearchData();
				String strOrderId = request.getParameter("orderId");
				if (strOrderId != null && !strOrderId.isEmpty()) {
					orderSearch.searchById(strOrderId);
					request.setAttribute("orderId", strOrderId);
				} else {
					String strEmail = request.getParameter("email");
					String strShipName = request.getParameter("shipName");
					String strShipPhoneNumber = request
							.getParameter("shipPhoneNumber");
					orderSearch.setPage(page);
					orderSearch.searchAdvance(null, null, null, strEmail, 0,
							strShipName, null, strShipPhoneNumber, null, null,
							0, "");
					request.setAttribute("email", strEmail);
					request.setAttribute("shipName", strShipName);
					request.setAttribute("shipPhoneNumber", strShipPhoneNumber);
				}
				request.setAttribute("orderSearch", orderSearch);
				request.setAttribute("url", request.getRequestURL().toString());
				request.getRequestDispatcher("/admin/pages/direct_sell.jsp")
						.forward(request, response);
			}

		} catch (Exception e) {
			System.out.println("Error when get list Order !");
			log.warning("Error when get list orders !");
			log.warning(e.toString());
			e.printStackTrace();
		}
	}
}
